﻿namespace DCHealthCheck.MvcWeb.Classes.DataServices {

    #region Usings
    using DCHealthCheck.Common;
    using DCHealthCheck.DomainModel;
    using DCHealthCheck.MvcWeb.Classes.ViewModels;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Linq.Expressions;
    using System.Threading;
    using System.Web;
    using System.Web.Mvc; 
    #endregion

    public class ProductsDataService : BaseDataService, IProductsDataService {

        #region Members
        private readonly IRepository<InstalledProduct, IEntityManager> ProductsRepository;

        private readonly Expression<Func<InstalledProduct, object>>[] ProductsIncludedEntities;
        #endregion

        #region Constructor
        public ProductsDataService(
            IRepository<DomainController, IEntityManager> dcRepository,
            IRepository<InstalledProduct, IEntityManager> productsRepository) : base(dcRepository) {
                if (productsRepository == null) {
                    throw new ArgumentNullException("productsRepository");
                }

            this.ProductsRepository = productsRepository;
            this.ProductsIncludedEntities = new Expression<Func<InstalledProduct, object>>[] {
                (x) => x.SystemInfo,
                (x) => x.SystemInfo.DomainController
            };
        }
        #endregion

        #region Methods
        private void BuildFilterSelectLists(ProductsViewModel viewModel) {
            var filteredDCIds = this.GetFilteredInstalledProducts(viewModel)
                .Select(x => x.SystemInfo.DomainController.Id)
                .Distinct()
                .ToList();

            base.BuildFilterSelectLists(filteredDCIds, viewModel);

            var selectListItem = new SelectListItem();
            selectListItem.Text = "(Any)";
            selectListItem.Value = string.Empty;
            viewModel.ProductNameSelectListItems.Add(selectListItem);

            var productNames = new List<string>();

            productNames = this.GetFilteredInstalledProducts(viewModel)
                .Select(x => x.Name)
                .Distinct()
                .OrderBy(x => x)
                .ToList();

            foreach (var name in productNames) {
                selectListItem = new SelectListItem();
                selectListItem.Text = name;
                if (!string.IsNullOrWhiteSpace(viewModel.ProductName) && string.Equals(viewModel.ProductName, name, StringComparison.OrdinalIgnoreCase)) {
                    selectListItem.Selected = true;
                }
                selectListItem.Value = name;
                viewModel.ProductNameSelectListItems.Add(selectListItem);
            }
        }

        private IQueryable<InstalledProduct> GetFilteredInstalledProducts(ProductsViewModel viewModel) {

            var installedProducts = this.ProductsRepository.Get(this.ProductsIncludedEntities);

            if (viewModel.SystemInfoId != Guid.Empty) {
                installedProducts = installedProducts.Where(x => x.SystemInfo.Id == viewModel.SystemInfoId);
            }
            else {
                if (viewModel.DomainControllerId != Guid.Empty) {
                    installedProducts = installedProducts.Where(x => x.SystemInfo.DomainController.Id == viewModel.DomainControllerId);
                }

                if (viewModel.Date != DateTime.MinValue) {
                    installedProducts = installedProducts.Where(x => x.SystemInfo.CheckDateTimeUTC == viewModel.Date);
                }
                else {
                    if (viewModel.StartDate.HasValue) {
                        installedProducts = installedProducts.Where(x => x.SystemInfo.CheckDateUTC >= viewModel.StartDate);
                    }
                    if (viewModel.EndDate.HasValue) {
                        installedProducts = installedProducts.Where(x => x.SystemInfo.CheckDateUTC <= viewModel.EndDate);
                    }
                }

                if (!string.IsNullOrWhiteSpace(viewModel.ADSite)) {
                    installedProducts = installedProducts
                        .Where(x => x.SystemInfo.DomainController.ADSite == viewModel.ADSite);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.Domain)) {
                    installedProducts = installedProducts
                        .Where(x => x.SystemInfo.DomainController.NetbiosDomain == viewModel.Domain);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.OSVersion)) {
                    installedProducts = installedProducts
                        .Where(x => x.SystemInfo.DomainController.OSVersion == viewModel.OSVersion);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.DCName)) {
                    installedProducts = installedProducts
                        .Where(x => x.SystemInfo.DomainController.SamAccountName == viewModel.DCName);
                }
                if (!string.IsNullOrWhiteSpace(viewModel.ProductName)) {
                    installedProducts = installedProducts.Where(x => x.Name == viewModel.ProductName);
                }
            } // if (this.SystemInfoId != Guid.Empty)

            return installedProducts;
        }

        public void ProcessData(ProductsViewModel viewModel) {
            Global.DefaultLog.DebugFormat("[ThreadId: {0}] {1}", Thread.CurrentThread.ManagedThreadId, Extensions.CurrentMethodName());

            try {
                viewModel.Initialize();
                var installedProducts = this.GetFilteredInstalledProducts(viewModel);
                viewModel.DisplayTotalResults = installedProducts.Count();

                #region Skip count, take, and sorting
                if (!string.IsNullOrWhiteSpace(viewModel.SortColumn)) {
                    if (viewModel.CurrentSortDirection == System.Web.Helpers.SortDirection.Ascending) {
                        viewModel.Products = installedProducts
                            .OrderBy(viewModel.SortColumn)
                            .Skip(viewModel.SkipCount.Value)
                            .Take(viewModel.TakeCount.Value)
                            .ToList();
                    }
                    else {
                        viewModel.Products = installedProducts
                            .OrderByDescending(viewModel.SortColumn)
                            .Skip(viewModel.SkipCount.Value)
                            .Take(viewModel.TakeCount.Value)
                            .ToList();
                    }
                }
                else {
                    viewModel.Products = installedProducts
                        .OrderBy(x => x.Name)
                        .Skip(viewModel.SkipCount.Value)
                        .Take(viewModel.TakeCount.Value)
                        .ToList();
                }
                #endregion

                viewModel.GetPageCounts();
                this.BuildFilterSelectLists(viewModel);
            }
            catch (Exception e) {
                Global.DefaultLog.DebugFormat("[ThreadId: {0}] {1} {2}", Thread.CurrentThread.ManagedThreadId, Extensions.CurrentMethodName(), e.VerboseExceptionString());
            }
        }
        #endregion
    }
}